package com.cup.ali.sms;

import java.text.SimpleDateFormat;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.cup.ali.config.AliConfig.AliSmsProperties;
import com.cup.ali.sms.bean.SmsRequest;
import com.cup.ali.sms.bean.SmsResponse;
import com.cup.ali.sms.vcode.Vcode;

/**
 * Created on 17/6/7.
 * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类，直接通过
 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可)
 * 工程依赖了2个jar包(存放在工程的libs目录下)
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 * <p>
 * 备注:Demo工程编码采用UTF-8
 * 国际短信发送请勿参照此DEMO
 */
@Component
@EnableConfigurationProperties({AliSmsProperties.class})
public class AliSmsService {

    private static final Logger logger = Logger.getLogger(AliSmsService.class);
    
    //产品名称:云通信短信API产品,开发者无需替换
  	public static final  String PRODUCT = "Dysmsapi";
    //产品域名,开发者无需替换
  	public static final  String DOMAIN = "dysmsapi.aliyuncs.com";
  	
  	@Autowired
  	private AliSmsProperties smsconfig;

    /**
     * 初始化
     * 1）可自助调整超时时间
     * 2）初始化acsClient,暂不支持region化
     *
     * @return
     * @throws ClientException
     */
    private IAcsClient init() throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", smsconfig.getConnecttimeout());
        System.setProperty("sun.net.client.defaultReadTimeout", smsconfig.getReadtimeout());
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsconfig.getAccesskey(), smsconfig.getAccesssecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);

        IAcsClient acsClient = new DefaultAcsClient(profile);
        return acsClient;
    }

    /**
     * @param sms
     * @return
     * @throws ClientException
     */
    public void sendSms(SmsRequest sms) throws Exception {

        Object havVcode = Vcode.build().get(sms.getPhoneNumbers());
        if (havVcode != null) {
            throw new Exception("重复获取验证码，60秒后再重试");
        }

        synchronized (AliSmsService.class) {
            new Thread("sms-send") {
                @Override
                public void run() {
                    try {
                        IAcsClient acsClient = init();
                        //组装请求对象-具体描述见控制台-文档部分内容
                        SendSmsRequest request = sms.buildRequest();

                        //hint 此处可能会抛出异常，注意catch
                        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

                        SmsResponse smsBack = SmsResponse.buildResponse(sendSmsResponse);
                        logger.info("response:" + JSON.toJSONString(smsBack));

                        //根据模板调整
                        Vcode.build().put(sms);
                    } catch (Exception e) {
                        logger.error("ali send message error:", e);
                    }
                }

            }.start();
        }
    }

    /**
     * 查明细接口
     * @param phoneNumber
     * @param sendDay
     * @return
     * @throws ClientException
     */
    public QuerySendDetailsResponse querySendDetails(String phoneNumber, String sendDay) throws ClientException {

        //可自助调整超时时间
        IAcsClient acsClient = init();

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(phoneNumber);
        //可选-流水号
//        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(sendDay));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }
}
